package com.gwt.tirso.gymkhana.server;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;


public class ConnectionManager {
	
	private static ConnectionManager cm;
	private Driver dBDriver = null;
	private String username = "root";
	private String password = "practica";

	private String driver = "com.mysql.jdbc.Driver";
	private String uri = "jdbc:mysql://127.0.0.1:3306/GymkhanaApp"; 
	
	private ConnectionManager() {
		try {
			dBDriver = (Driver) Class.forName(driver).newInstance();
			DriverManager.registerDriver(dBDriver);
		}catch (Exception e) {
			System.err.println("Unable to register JDBC Driver");
			e.printStackTrace();
		}
	}
	

	public static synchronized ConnectionManager getInstance() {
		if (cm == null) {
			cm = new ConnectionManager();
		}
		return cm;
	}

    public Connection checkOut() {
    	Connection conn = null;

    	try {
    		conn = (Connection) DriverManager.getConnection(uri, username ,password);
    	}catch (Exception e) {
    		System.err.println("Unable to open a new JDBC connection");
    		e.printStackTrace();
    	}

    	return conn;
    }

    public void checkIn(Connection conn) {
    	try {
    		conn.close();
    	}catch (SQLException e) {
    		e.printStackTrace();
    	}
    }
    
    protected void finalize() {
    	try {
    		DriverManager.deregisterDriver(dBDriver);
    	}catch (SQLException e) {
    		System.err.println("Unable to deregister JDBC driver");
    		e.printStackTrace();
    	}
    }
}
